//
//  HYLTableViewController.m
//  多图片下载线程间的通信
//
//  Created by hyl on 16/7/20.
//  Copyright © 2016年 hyl. All rights reserved.
//

#import "HYLTableViewController.h"
#import "HYLApp.h"
@interface HYLTableViewController ()
/** appArr*/
@property (nonatomic,strong) NSArray *appArr;
/** picDic*/
@property (nonatomic,strong) NSMutableDictionary *imageCache;
/** operationCache*/
@property (nonatomic,strong) NSMutableDictionary *operationCache;
/** queue*/
@property (nonatomic,strong) NSOperationQueue *queue;
@end

@implementation HYLTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}
#pragma mark -operationCache
-(NSMutableDictionary *)operationCache{
    if (!_operationCache) {
        _operationCache=[NSMutableDictionary dictionary];
    }
    return _operationCache;
}

#pragma mark - queue
-(NSOperationQueue *)queue{
    if (!_queue) {
        _queue=[[NSOperationQueue alloc]init];
    }
    return _queue;
}

#pragma mark - imageCache
-(NSMutableDictionary *)imageCache{
    if (_imageCache==nil) {
        _imageCache=[NSMutableDictionary dictionary];
    }
    return _imageCache;
}

#pragma mark - appArr
-(NSArray *)appArr{
    if (_appArr==nil) {
        NSMutableArray *appMArr=[NSMutableArray array];
        NSString *path=[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
//                NSDictionary *appDic=[NSDictionary dictionaryWithContentsOfFile:path];
        _appArr=[NSArray arrayWithContentsOfFile:path];
        for (NSDictionary *dic in _appArr) {
            HYLApp *app=[HYLApp appWithDic:dic];
            [appMArr addObject:app];
        }
        _appArr=appMArr;
    }
    return _appArr;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.appArr.count;
}

//1.1先从缓存中找
//1.2再从沙盒中找
//1.3最后下载图片
//1.4下载图片后添加到缓存与沙盒中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"app" forIndexPath:indexPath];
    
    HYLApp *app=self.appArr[indexPath.row];
    NSString *path=app.icon;
    
    __block UIImage *image=self.imageCache[path];
    if (image) {//要找图片有
        cell.imageView.image=image;
        NSLog(@"缓存中找到");
    }else{//没有
        //获得Library/Caches文件夹:NSCachesDirectory，还有其他
        NSString *pathCache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        //获得文件名
        NSString *fileName=[app.icon lastPathComponent];
        //获得文件全路径
        NSString *file=[pathCache stringByAppendingPathComponent:fileName];
        //加载沙盒中图片
        NSData *dataWithFile=[NSData dataWithContentsOfFile:file];
        if (dataWithFile) {
            NSLog(@"沙盒中找到");
            image=[UIImage imageWithData:dataWithFile];
//           缓存中加入图片
            self.imageCache[path]=image;
            cell.imageView.image=image;
        }else{
            if (!self.operationCache[path]) {
                
                NSBlockOperation *bo=[NSBlockOperation blockOperationWithBlock:^{
                    NSLog(@"下载");
                    NSURL *url=[NSURL URLWithString:path];
                    NSData *dataWithUrl=[NSData dataWithContentsOfURL:url];
                    image=[UIImage imageWithData:dataWithUrl];
                    //          缓存与沙盒中加入图片
                    self.imageCache[path]=image;
                    [dataWithUrl writeToFile:file atomically:YES];
                    
                    
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        cell.imageView.image=image;
                    }];
                    self.operationCache[path]=bo;
                }];
                [self.queue addOperation:bo];
            }
            
        }
    }
    // Configure the cell...

    cell.textLabel.text=app.name;
    cell.detailTextLabel.text=app.download;
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
